package com.java.base.exercise.current;

import java.util.concurrent.*;

/**
 * @Author RenPu
 * @Date 2021/9/30 11:18
 * @Version 1.0
 * @Description: 实现线程池的监控，beforeExecute，afterExecute，terminated
 **/
public class MainThreadPoolExecuteDemo {


    public static void main(String[] args) throws Exception {

        Thread.sleep(5000L);

        MainThreadPoolExecute mainThreadPoolExecute = new MainThreadPoolExecute(5, 5, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>());


        for (int i = 0; i < 4; i++) {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(3000L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };
            mainThreadPoolExecute.execute(runnable);
        }
        mainThreadPoolExecute.shutdown();
        System.out.println("Thread Main  is dead ! ! ! !");
    }


    static class MainThreadPoolExecute extends ThreadPoolExecutor {

        public MainThreadPoolExecute(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
            super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
        }


        /**
         * 执行前调用的方法
         *
         * @param paramThread
         * @param runnable
         */
        @Override
        protected void beforeExecute(Thread paramThread, Runnable runnable) {

            System.out.println("work_task_before:" + paramThread.getName());

        }


        /**
         * 执行后调用的方法
         *
         * @param runnable
         * @param throwable
         */
        @Override
        protected void afterExecute(Runnable runnable, Throwable throwable) {
            super.afterExecute(runnable, throwable);
            System.out.println("work_task_after worker thread is : " + runnable);

        }


        /**
         * 请求结束调用的，终止方法
         */
        @Override
        protected void terminated() {

            System.out.println("terminated getCorePoolSize : " + this.getCorePoolSize() +
                    "getPoolSize : " + this.getPoolSize() + "getTaskCount :" + this.getTaskCount()
                    + "getCompleteTaskCount : " + this.getCompletedTaskCount()
                    + "getLargePoolSize :" + this.getLargestPoolSize() + "getActiveCount :" + this.getActiveCount());
            System.out.println(" ThreadPoolExecutor terminated ! ! !");

        }


    }


}
